<?php
/**
 ***********************************************************************************************************************
 * syslog方式记录日志
 ***********************************************************************************************************************
 */

namespace artisan\logger\storage;

/**
 * Class syslog
 * @package artisan\logger\storage
 */
class syslog
{
    /**
     * @var array
     */
    private $logMap = [
        'DEBUG'     => LOG_DEBUG,
        'INFO'      => LOG_INFO,
        'NOTICE'    => LOG_NOTICE,
        'WARNING'   => LOG_WARNING,
        'ERROR'     => LOG_ERR,
        'CRITICAL'  => LOG_CRIT,
        'ALERT'     => LOG_ALERT,
        'EMERGENCY' => LOG_EMERG,
    ];

    /**
     * @var array
     */
    private $logLocals = [
        'local1' => LOG_LOCAL1,
        'local2' => LOG_LOCAL2,
        'local3' => LOG_LOCAL3,
        'local4' => LOG_LOCAL4,
        'local5' => LOG_LOCAL5,
        'local6' => LOG_LOCAL6,
        'local7' => LOG_LOCAL7,
    ];

    /**
     * @param $log
     */
    public function write($log)
    {
        $ident = globalConfig('log.syslog.ident') ?: 'artisan';
        $local = globalConfig('log.syslog.local') ?: 'local4';
        if (openlog($ident, LOG_PID, $this->logLocals[$local])) {
            $slog = $this->format($log);
            if(strlen($slog) < 900){
                syslog($this->logMap[$log['level']], $slog);
            } else {
                //如果上层参数isRecordAll确定要记录全日志，就不截断
                empty($log['isRecordAll'])&&$log['message'] = substr($log['message'], 0, 800) . '……[日志长度限制1024字节]';
                syslog($this->logMap[$log['level']], $this->format($log));
            }
        }
    }

    /**
     * @param $log
     * @return mixed|string
     */
    private function format($log)
    {
        return json_encode($log, JSON_UNESCAPED_UNICODE);
    }

    /**
     * close log
     */
    public function __destruct()
    {
        closelog();
    }
}